/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.demo.ehcache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.Statistics;
import org.vacoor.nothing.common.util.Resources;

import java.io.InputStream;
import java.io.Serializable;

/**
 * @author: vacoor
 */
public class EhcacheDemo {
    private static final String CACHE_NAME = "demoCache";

    private Cache cache;

    public EhcacheDemo() {
        InputStream in = Resources.getResourceAsStream("conf/ehcache/ehcache-cluster-rmi.xml");
        CacheManager cacheManager = new CacheManager(in);
        cache = cacheManager.getCache(CACHE_NAME);
        cache.flush();
        String[] cacheNames = cacheManager.getCacheNames();
        for (String name : cacheNames) {
            Cache chache = cacheManager.getCache(name);
            Statistics statistics = chache.getStatistics();
            // 命中次数
            long cacheHits = statistics.getCacheHits();
            // 失效次数
            long cacheMisses = statistics.getCacheMisses();
            long total = cacheHits + cacheMisses;
            total = total > 0 ? total : 1;

            float hitPercent = cacheHits * 1.0F / total;    // 命中率
        }
    }

    public Object get(Serializable key) {
        return cache.get(key).getObjectValue();
    }

    public void put(Serializable key, Serializable value) {
        cache.put(new Element(key, value));
    }

    public static void main(String[] args) {
        EhcacheDemo demo = new EhcacheDemo();
        demo.put("foo", "bar");

        Object value = demo.get("foo");
        System.out.println(value);
    }
}
